package com.situ.mall.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.situ.mall.common.util.JsonUtil;
import com.situ.mall.common.util.RedisUtil;
import com.situ.mall.pojo.entity.Category;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.situ.mall.service.ICategoryService;

@Controller
public class IndexController {
	@Autowired
	private ICategoryService categoryService;
	@Autowired
	private RedisUtil redisUtil;

	// private HashMap<String, Object> map = new HashMap<>();

	@RequestMapping("/")
	public String index(Model model) {
		/*List<Category> list = (List<Category>) map.get("topCategoryList");
		if (list == null) {
			List<Category> topCategoryList = categoryService.selectTopCategoryList();
			map.put("topCategoryList", topCategoryList);
		}*/

		/**
		 * 1. 后台运营系统，一旦分类发生更改，就可以删除缓存，然后重置
		 * 2. 定时重置，比如每天凌晨三点重置
		 * 3. 如果是类似于首页轮播图做到redis缓存，每个轮播图都有可能是一个广告，
		 *   每个广告都会有一个过期时间，过期了，再重置
		 */

		List<Category> topCategoryList = new ArrayList<>();
		String topCategoryListJson  = redisUtil.get("topCategoryListJson");
		// if (topCategoryListJson == null || "".equals(topCategoryListJson) ) {
        if (StringUtils.isBlank(topCategoryListJson)) {
            // redis里面没有这个数据
			topCategoryList = categoryService.selectTopCategoryList();
			// 查出数据来，把数据写到redis里面，下一次访问时候就直接从redis里面拿出来
			topCategoryListJson = JsonUtil.objectToJson(topCategoryList);
			redisUtil.set("topCategoryListJson", topCategoryListJson);
		} else {
			// redis有这个数据
			topCategoryList = JsonUtil.jsonToList(topCategoryListJson, Category.class);
		}

		List<Category> secondCategoryList = new ArrayList<>();
		String secondCategoryListJson  = redisUtil.get("secondCategoryListJson");
		if (secondCategoryListJson == null || "".equals(secondCategoryListJson) ) {
			// redis里面没有这个数据
			secondCategoryList = categoryService.selectSecondCategoryList();
			// 查出数据来，把数据写到redis里面，下一次访问时候就直接从redis里面拿出来
			secondCategoryListJson = JsonUtil.objectToJson(secondCategoryList);
			redisUtil.set("secondCategoryListJson", secondCategoryListJson);
		} else {
			// redis有这个数据
			secondCategoryList = JsonUtil.jsonToList(secondCategoryListJson, Category.class);
		}

		model.addAttribute("topCategoryList", topCategoryList);
		model.addAttribute("secondCategoryList", secondCategoryList);

		return "index";
	}
}
